package com.cyf.smartCity.service.impl;

import com.cyf.activemq.service.MqService;
import com.cyf.db.bean.ApiUser;
import com.cyf.db.bean.LocalDevice;
import com.cyf.db.mapper.ApiUserMapper;
import com.cyf.db.mapper.ApiUserParkingMapper;
import com.cyf.db.mapper.smartCity.LocalDeviceMapper;
import com.cyf.db.mapper.smartCity.LocalInParkingMapper;
import com.cyf.redis.RedisService;
import com.cyf.service.bean.CustomException;
import com.cyf.smartCity.bean.*;
import com.cyf.smartCity.service.CenterService;
import com.cyf.util.DateUtil;
import com.cyf.util.ObjectMapperUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.cyf.smartCity.bean.ApiBusinessRsp.SUCCESS;

@Service
@Transactional
@Slf4j
public class CenterServiceImpl implements CenterService {
    @Autowired
    private RedisService redisService;
    @Autowired
    private LocalInParkingMapper localInParkingMapper;
    @Autowired
    private ApiUserMapper apiUserMapper;
    @Autowired
    private ApiUserParkingMapper apiUserParkingMapper;
    @Autowired
    private MqService mqService;
    @Autowired
    private LocalDeviceMapper localDeviceMapper;



    @Override
    public WechatParkGetDeviceCurCarInfoRsp getDeviceCurCarInfo(WechatParkGetDeviceCurCarInfoReq req) {
        WechatParkGetDeviceCurCarInfoRsp rsp = new WechatParkGetDeviceCurCarInfoRsp();

        Object object = redisService.get(req.getParkingId() + "-" + req.getLocalDeviceId());
        if (object == null) {
            rsp.setResult(WechatParkGetDeviceCurCarInfoRsp.FAIL);
            rsp.setStrError("未找到信息！");
            return rsp;
        }

        MqNoticeDeviceCurInfoReq mqReq;
        try {
            mqReq = ObjectMapperUtils.readValue(object.toString(), MqNoticeDeviceCurInfoReq.class);
        } catch (IOException e) {
            log.error("{}", e);
            rsp.setResult(WechatParkGetDeviceCurCarInfoRsp.FAIL);
            rsp.setStrError("未找到信息！");
            return rsp;
        }
        rsp.setInDevice(mqReq.getInDevice());
        rsp.setPlate(mqReq.getPlate());
        rsp.setInImageId(mqReq.getInImageId());
        rsp.setOutImageId(mqReq.getOutImageId());
        rsp.setFeeRspId(mqReq.getFeeRspId());
        rsp.setActualFee(mqReq.getActualFee());
        rsp.setFeeGroupName(mqReq.getFeeGroupName());
        rsp.setFeeMemo(mqReq.getFeeMemo());
        rsp.setAlreadyOut(false);
        rsp.setOrderNo(mqReq.getOrderNo());
        if (mqReq.getTime() != null) {
            rsp.setTime(DateUtil.convertDate2Str(mqReq.getTime(), DateUtil.FORMAT_YYYY_MM_DD_HH_MI_SS));
        }
        if (!rsp.getInDevice()) {
            Integer count = localInParkingMapper.countByParkingIdAndPlate(mqReq.getParkingId(), mqReq.getPlate());
            if (count == null || count == 0) {
                rsp.setAlreadyOut(true);
            }
        }
        rsp.setResult(WechatParkGetDeviceCurCarInfoRsp.SUCCESS);
        return rsp;
    }

    @Override
    public ApiOpenBarrierRsp openBarrier(ApiOpenBarrierReq req) {
        ApiOpenBarrierRsp rsp = new ApiOpenBarrierRsp();
        rsp.setResult(ApiBusinessRsp.FAIL);
        try {
            if (req.getDeviceId() == 0) {
                if (req.getPlate().length() < 7) {
                    rsp.setStrError("车牌号码不正确！");
                    return rsp;
                }
            }
            ApiUser apiUser = checkToken(req.getToken());
            // 查询 parkingId
            List<Integer> parkingIds = apiUserParkingMapper.getParkingIdByApiUserId(apiUser.getId());
            if (parkingIds == null || parkingIds.size() == 0 || !parkingIds.contains(req.getParkingId())) {
                rsp.setStrError("没有该车场！");
                return rsp;
            }

            if (req.getFeeRspId() == null) {
                req.setFeeRspId(0);
            }

            mqService.openBarrier(req.getPlate(), req.getParkingId(), req.getDeviceId(), req.getFeeRspId());
            rsp.setResult(SUCCESS);
        } catch (CustomException e) {
            rsp.setStrError(e.getMessage());
        } catch (Exception e) {
            log.error("获取停车费异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public ApiCloseBarrierRsp closeBarrier(ApiCloseBarrierReq req) {
        ApiCloseBarrierRsp rsp = new ApiCloseBarrierRsp();
        rsp.setResult(ApiBusinessRsp.FAIL);
        try {
            ApiUser apiUser = checkToken(req.getToken());
            List<Integer> parkingIds = apiUserParkingMapper.getParkingIdByApiUserId(apiUser.getId());
            if (parkingIds == null || parkingIds.size() == 0 || !parkingIds.contains(req.getParkingId())) {
                rsp.setStrError("没有该车场！");
                return rsp;
            }
            mqService.closeBarrier(req.getParkingId(), req.getDeviceId());
            rsp.setResult(SUCCESS);
        } catch (CustomException e) {
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public WechatParkListDeviceRsp listDevice(WechatParkBasicReq req) {
        WechatParkListDeviceRsp rsp = new WechatParkListDeviceRsp();
        List<LocalDevice> deviceList = localDeviceMapper.listBaseInfoByParkingId(req.getParkingId());
        if (CollectionUtils.isNotEmpty(deviceList)) {
            List<WechatParkListDeviceRsp.Info> list = new ArrayList<>();
            for (LocalDevice device : deviceList) {
                WechatParkListDeviceRsp.Info item = new WechatParkListDeviceRsp.Info();
                item.setLocalDeviceId(device.getLocalDeviceId());
                item.setName(device.getName());
                list.add(item);
            }
            rsp.setDeviceList(list);
        }
        rsp.setResult(WechatBasicRsp.SUCCESS);
        return rsp;
    }

    /**
     * 检验token是否存在
     * @param token 唯一标识
     * @return ApiUser
     * @throws CustomException
     */
    public ApiUser checkToken(String token) throws CustomException {
        ApiUser apiUser = apiUserMapper.getByToken(token);
        if (apiUser == null) {
            throw new CustomException("参数token错误");
        }
        return apiUser;
    }

}

